
import { useState } from 'react'
import { useHistory } from 'react-router-dom'
import { CHOOSE_SEARCH_ADDRESS } from 'src/redux/action-type'
import { searchNearby } from 'src/api/getData'
import { Header } from 'src/components'
import './index.scss'
import { useDispatch } from 'react-redux'

// 搜索位置
const SearchPosition = () => {

    const dispatch = useDispatch(0)
    const history = useHistory();
    const [searchValue, setSearchValue] = useState() //输入的搜索内容
    const [searchData, setSearchData] = useState()//搜索的结果

    //搜索
    const searchPlace = async (e) => {
        e.preventDefault()
        if (searchValue) {
            let res = await searchNearby(searchValue);
            setSearchData(res)
        }
    }
    //选择搜素结果
    const choooedAddress = (item) => {
        dispatch({
            type: CHOOSE_SEARCH_ADDRESS,
            place: item
        })

        history.go(-1);
    }

    return <div className="search_address_page">
        <section>
            <Header title="搜索" goBack></Header>
            <form className="search_form">
                <input type="search" name="search" placeholder="请输入小区/写字楼/学校等"
                    value={searchValue}
                    onInput={(e) => setSearchValue(e.target.value)}
                />
                <button onClick={searchPlace}>搜索</button>
            </form>
            {
                searchData ? <ul className="address_list">
                    {
                        searchData.map((item, index) => {
                            return <li key={index} onClick={() => choooedAddress(item)}>
                                <h4>{item.name}</h4>
                                <p>{item.address}</p>
                            </li>
                        })
                    }

                </ul>
                    : <div className="empty_tips">
                        <p>找不到地址？</p>
                        <p>尝试输入小区、写字楼或学校名</p>
                        <p>详细地址（如门牌号等）可稍后输入哦</p>
                    </div>
            }
        </section>
    </div>
}

export default SearchPosition